# Copyright 2024 Daniel DeGrasse <daniel@degrasse.com>
# SPDX-License-Identifier: Apache-2.0

# Based on Nordic's implementation of VPR launcher, which is
# Copyright (c) 2024 Nordic Semiconductor ASA

if(SB_CONFIG_SECOND_CORE_MCUX_LAUNCHER)
  # M7 is the boot core, and will start secondary core
  set(launcher_core "cm7")
  string(REPLACE "/" ";" launcher_quals ${BOARD_QUALIFIERS})
  list(LENGTH launcher_quals launcher_quals_len)
  list(GET launcher_quals 1 launcher_soc)

  string(CONCAT launcher_board ${BOARD} "/" ${launcher_soc} "/" ${launcher_core})

  set(launcher_image "cm4_launcher")

  ExternalZephyrProject_Add(
    APPLICATION ${launcher_image}
    SOURCE_DIR ${ZEPHYR_BASE}/samples/basic/minimal
    BOARD ${launcher_board}
  )

  set(remote_dir "${APPLICATION_BINARY_DIR}/${DEFAULT_IMAGE}/zephyr/include/public")

  # Enable CONFIG_SECOND_CORE_MCUX and CONFIG_BUILD_OUTPUT_HEX
  # for the application running on the CM4 core
  set_config_bool(${DEFAULT_IMAGE} CONFIG_SECOND_CORE_MCUX 1)
  set_config_bool(${DEFAULT_IMAGE} CONFIG_BUILD_OUTPUT_HEX 1)

  # Enable CONFIG_SECOND_CORE_MCUX for the image running on the CM7 core
  set_config_bool(${launcher_image} CONFIG_SECOND_CORE_MCUX 1)
  # Set the initial include path for the image running on the CM7 core to
  # include the image header output by the CM4 image
  set_config_string(${launcher_image} CONFIG_SECOND_CORE_MCUX_REMOTE_DIR ${remote_dir})

  # Add dependency on CM4 core image to CM7 image. This way,
  # the CM4 image will be built first. This is required because the M7 image
  # depends on output headers generated by the M4 image.
  add_dependencies(${launcher_image} ${DEFAULT_IMAGE})
  sysbuild_add_dependencies(CONFIGURE ${launcher_image} ${DEFAULT_IMAGE})
endif()
